/**
 * Copyright (c) 2015-2017, Javen Zhou  (javen205@126.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */

package com.javen.weixin.service;

import java.util.Date;

import com.javen.weixin.common.model.Qrcode;
import com.jfinal.kit.Kv;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.SqlPara;

/**
 * 二维码推广
 * 
 * @author Javen 2017年7月14日
 */
public class QrcodeService {
	static Log log = Log.getLog(QrcodeService.class);
	public static final QrcodeService me = new QrcodeService();
	private final Qrcode dao = new Qrcode().dao();
	/**
	 * 保存
	 * @param appId
	 * @param expire_seconds
	 * @param ticket
	 * @param sceneId
	 * @param sceneStr
	 * @param url
	 * @return
	 */
	public boolean save(Qrcode qrcode,String appId, int expire_seconds, String ticket, int sceneId, String sceneStr, String url) {
		boolean update = true;
		boolean success = false;
		if (null == qrcode) {
			update = false;
			qrcode = new Qrcode();
		}
		
		qrcode.setAppId(appId);
		qrcode.setExpireSeconds(expire_seconds);
		qrcode.setTicket(ticket);
		qrcode.setSceneId(sceneId);
		qrcode.setSceneStr(sceneStr);
		qrcode.setUrl(url);
		qrcode.setUpdateTime(new Date());
		qrcode.setCreateTime(new Date());
		if (update) {
			success = qrcode.save();
		}else {
			success = qrcode.update();
		}
		return success;
	}
	/**
	 * 根据id查询Qrcode
	 * @param id
	 * @return
	 */
	public Qrcode getQrcodeById(int id){
		return dao.findById(id);
	}
	/**
	 * 根据ticket以及appId 查询Qrcode
	 * @param ticket
	 * @param appId
	 * @return
	 */
	public Qrcode getQrcodeByTicket(String ticket, String appId){
		Kv para = Kv.by("ticket",ticket).set("app_id", appId).set("status",1);
		SqlPara sqlPara = dao.getSqlPara("qrcode.getQrcodeByTicket", para);
		return dao.findFirst(sqlPara);
	}
	/**
	 * 根据sceneId以及appId 查询Qrcode
	 * @param sceneId
	 * @param appId
	 * @return
	 */
	public Qrcode getQrcodeBySceneId(int sceneId, String appId){
		Kv para = Kv.by("scene_id",sceneId).set("app_id", appId).set("status",1);
		SqlPara sqlPara = dao.getSqlPara("qrcode.getQrcodeBySceneId", para);
		return dao.findFirst(sqlPara);
	}
	/**
	 * 根据sceneStr以及appId 查询Qrcode
	 * @param sceneStr
	 * @param appId
	 * @return
	 */
	public Qrcode getQrcodeBySceneStr(String sceneStr, String appId){
		Kv para = Kv.by("scene_str",sceneStr).set("app_id", appId).set("status",1);
		SqlPara sqlPara = dao.getSqlPara("qrcode.getQrcodeBySceneStr", para);
		return dao.findFirst(sqlPara);
	}

}
